package bbsimon.first.bookshop;

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import bbsimon.first.model.shopcart.*;

public class ShopServlet extends HttpServlet {
	public void doPost(HttpServletRequest request, HttpServletResponse res)
		throws IOException, ServletException {
			res.setContentType("text/html");
			
			PrintWriter out = res.getWriter();

			//Create http session
			HttpSession session = request.getSession();

			//create a list of books using ArrayList<BookModel> to store them
			BookModel bm = new BookModel("Hello World", 19.2, new String[]{"bbsimon", "Harkin"});
			List<BookModel> list = new ArrayList<BookModel>();
			list.add(bm);
			bm = new BookModel("Cpp How to Program", 30.2, new String[]{"ABC", "Stevy"});
			list.add(bm);
			bm = new BookModel("JAVA Master", 109.32, new String[]{"Hellen", "Kingston"});
			list.add(bm);
			bm = new BookModel("Algorithm Introduction", 23.43, new String[]{"Delon", "Chameron"});
			list.add(bm);
			bm = null;
			//Get cart from sessions, if there's no one
			//then create a new one
			CartModel cm = (CartModel)session.getAttribute("cart");
			if(cm == null)
				cm = new CartModel();

			//check requst parameter
			String bookname = (String)request.getParameter("addBookName");
			if(bookname != null) {
				for(BookModel book : list) {
					if(book.getBookName().equals(bookname)) {
						cm.add(book);
						break;
					}
				}
			}
			bookname = (String)request.getParameter("rmBookName");
			if(bookname != null) {
				for(BookModel book2 : list) {
					if(book2.getBookName().equals(bookname)) {
						cm.remove(book2);
						break;
					}
				}
			}

			//Bind to requst
			request.setAttribute("books", list);

			//store cart into the session
			session.setAttribute("cart", cm);
			RequestDispatcher view = request.getRequestDispatcher("bookshop.jsp");
			view.forward(request, res);
		}

	public void doGet(HttpServletRequest request, HttpServletResponse res)
		throws IOException, ServletException {
			doPost(request, res);
		}

}

